package cn.doitedu.javase.thread;

import java.util.Random;

public class _02_线程同步方式3 {

    static Integer count = 0;
    static Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(new Adder());
        Thread t2 = new Thread(new Adder());

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println(count);
    }


    // 利用 synchronized 将方法声明为  线程同步方法
    // 多个线程调用这个方法时，就需要先获取到锁
    public static synchronized void add() {
        for (int i = 0; i < 5000; i++) {
            count++;
        }
    }


    static class Adder implements Runnable {
        Random random = new Random();

        @Override
        public void run() {
            System.out.println(random.nextInt(100));
            add();
        }


    }


}
